﻿<%@ WebHandler Language="C#" Class="Captcha" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Drawing.Imaging;
using System.IO;
using System.Web.SessionState;

public class Captcha : IHttpHandler, IReadOnlySessionState
{    
    public void ProcessRequest (HttpContext context) {
        context.Session["Captcha"] = SetVerificationText();
        savesessiontocookie(context);
        string[] fonts = { "Arial Black", "Lucida Sans Unicode", "Comic Sans MS" };
        Bitmap bmpOut = new Bitmap(100, 30);
        Graphics g = Graphics.FromImage(bmpOut);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        HatchBrush brush = new HatchBrush(HatchStyle.OutlinedDiamond, Color.White, Color.Wheat);
        g.FillRectangle(brush, 0, 0, 100, 30);
        Random rand = new Random();
        g.DrawString(context.Session["Captcha"].ToString(), new Font(fonts[rand.Next(fonts.Length)], 15), new SolidBrush(Color.Red), 0, 0);
        MemoryStream ms = new MemoryStream();
        bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        byte[] bmpBytes = ms.GetBuffer();
        bmpOut.Dispose();
        ms.Close();
        context.Response.BinaryWrite(bmpBytes);
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
    private void savesessiontocookie(HttpContext context)
    {
        try
        {
            HttpCookie cookie = new HttpCookie("captcha", context.Session["Captcha"].ToString());
            cookie.Expires = DateTime.Now.AddHours(1);
            context.Response.Cookies.Add(cookie);
        }
        catch
        {
        }
    }
    public string SetVerificationText()
    {
        const byte LENGTH = 6;
        const string chars = "23456789ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz";
        StringBuilder strCaptcha = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < LENGTH; i++)
        {
            string str = chars[ran.Next(chars.Length)].ToString();
            strCaptcha.Append(str);
        }
        int no = ran.Next();
        return strCaptcha.ToString();
    }

}